

package com.sq.partner.manager.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.sql.Clob;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sq.partner.manager.common.Config;
import com.sq.partner.manager.mybatis.model.*;
import com.sq.partner.manager.service.*;
import com.sq.partner.manager.util.*;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.dao.INlifePlanDao;
import com.sq.partner.manager.dao.INlifeProdDao;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

/**
 * @date 2015-11-02 新意健险方案配置
 */
@Controller
@RequestMapping("/nlifePlanConfig")
public class NlifePlanConfigController {
	private static Logger logger = LogUtil.getLog(NlifePlanConfigController.class);
	@Resource
	private INlifePlanDao nlifePlanDao;
	@Resource
	private INlifePlanConfigService nlifePlanConfigService;
	@Resource
	private INlifeProdDao nlifeProdDao;
	@Resource
	TradPlanSaleService tradPlanSaleService;
	@Resource
	private ITradInsuPlanGroupService insuPlanGroupService;
	@Resource
	private IGatewaySubChannelService subChannelService;
	@Resource
	private TradSmsTemplateService tradSmsTemplateService;
	@Resource
	private CoinPlanConfigService coinPlanConfigService;
	@Resource
	private SaleConfigService saleConfigService;
	@Resource
	private CoinFeeConfigService coinFeeConfigService;
	@Resource
	private IGatewayClearCacheManager gatewayClearCacheManager;
	@Resource
	private TradEmailTemplateService tradEmailTemplateService;
	@Resource
	private RuleInfoService ruleInfoService;
	@Resource
	private INlifeProdConfigService iNlifeProdConfigService;
	@Resource
	private IGatewayChannelInfoConfigService iGatewayChannelInfoConfigService;

	/**
	 * 跳转方案列表页面
	 */
	@RequestMapping(value = "/list")
	public String list() throws Exception {
		return "nlifeProduct/planConfig/list";
	}

	/**
	 * 分页条件查询合作伙伴
	 * @param session
	 * @param page
	 * @param channelInfo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryChannelInfoPageByCriteria")
	@ResponseBody
	public Page<GatewayChannelInfo> queryChannelInfoPageByCriteria(HttpSession session,Page<GatewayChannelInfo> page,GatewayChannelInfo channelInfo) throws Exception{
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		page.setDepts(gatewayuser.getDepts());
		page.setType(channelInfo);

		page = nlifePlanConfigService.queryChannelInfoPageByCriteria(page);

		return page;
	}
	/**
	 * 方案新增界面分页条件查询合作伙伴
	 * @param session
	 * @param page
	 * @param channelInfo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryChannelInfoPageByCriteria1")
	@ResponseBody
	public Page<GatewayChannelInfo> queryChannelInfoPageByCriteria1(HttpSession session,Page<GatewayChannelInfo> page,GatewayChannelInfo channelInfo) throws Exception{
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		page.setDepts(gatewayuser.getDepts());
		page.setType(channelInfo);

		page = nlifePlanConfigService.queryChannelInfoPageByCriteria1(page);

		return page;
	}
	/**
	 * 分页条件查询方案
	 * @param session
	 * @param page
	 * @param nlifePlan
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryNlifePlanPageByCriteria")
	@ResponseBody
	public Page<Map<String,Object>> queryNlifePlanPageByCriteria(HttpSession session,Page<Map<String,Object>> page,NlifePlan nlifePlan) throws Exception{

		GatewayUser user=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		String privilegedDeptStr = user.getDepartmentStr();
		String userCodes=com.sq.partner.manager.common.Config.getProp("imple.nlife.userCodes");
		/**方案导出，查询是否有导出权限*/
		String[] codes=forPlans(userCodes);
		boolean flag=false;
		logger.info("登录用户名："+user.getUserCode()+"   配置的用户名： "+userCodes);
		if(codes!=null&&codes.length>0){
			flag=Arrays.asList(codes).contains(user.getUserCode());
		}
		Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
		paramMap.put("privilegedDeptStr", privilegedDeptStr==null?"''":privilegedDeptStr.substring(1, 3));
		paramMap.put("partnerNo", nlifePlan.getPartnerNo()==null?"":nlifePlan.getPartnerNo());
		paramMap.put("planNo", nlifePlan.getPlanNo()==null?"":nlifePlan.getPlanNo());
		paramMap.put("planName", nlifePlan.getPlanName()==null?"":nlifePlan.getPlanName());
		paramMap.put("prodCode", nlifePlan.getProdCode()==null?"":nlifePlan.getProdCode());
		paramMap.put("checkStatus", nlifePlan.getCheckStatus()==null?"":nlifePlan.getCheckStatus());

		page.setMap(paramMap);
		page.setObj(flag);
		page = nlifePlanConfigService.queryNlifePlanPageByCriteria(page);
		return page;
	}

	/**
	 * 删除方案
	 * @param nlifePlan
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/delNlifePlan")
	@ResponseBody
	public Result delNlifePlan(NlifePlan nlifePlan,HttpSession session) throws Exception{

		Result result = nlifePlanConfigService.delNlifePlan(nlifePlan,session);

		return result;
	}

	/**
	 * 跳转至新增方案页面
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/toAddNlifePlan")
	public String toAddNlifePlan(ModelMap model) throws Exception {

		nlifePlanConfigService.toAddNlifePlan(model);

		return "nlifeProduct/planConfig/addOrEdit";
	}

	//查询短信模板信息
	@RequestMapping(value = "/loadTemplate")
	public @ResponseBody TradSmsTemplate loadTemplate(String smsTemplateCode) throws Exception{
		return tradSmsTemplateService.queryTradeByCode(smsTemplateCode);
	}

	/**
	 * 跳转至编辑页面
	 * @param model
	 * @param planNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/toEditNlifePlan")
	public String toEditNlifePlan(ModelMap model, String planNo) throws Exception {
		nlifePlanConfigService.toEditNlifePlan(model,planNo);
		/**编辑不显示上线按钮*/
		model.put("ptnEnv", "display:none");
		return "nlifeProduct/planConfig/addOrEdit";
	}

	/**
	 * 跳转至复制新增页面
	 * @param model
	 * @param planNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/toCopyAddNlifePlan")
	public String toCopyAddNlifePlan(ModelMap model, String planNo) throws Exception {
		nlifePlanConfigService.toCopyAddNlifePlan(model,planNo);
		return "nlifeProduct/planConfig/addOrEdit";
	}

	/**
	 * 跳转健康告知界面
	 * @param model
	 * @param
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/toNlifeHealthyInfoConfig")
	public String toNlifeHealthyInfoConfig(ModelMap model) throws Exception {

		return "nlifeProduct/planConfig/healthyInfoList";
	}

	/**
	 * 添加/编辑成功后返回方案列表页面
	 * @param flag
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/successBack")
	public String successBack(HttpServletRequest request, String flag) throws Exception {
		request.setAttribute("flag", flag);

		return "nlifeProduct/planConfig/list";
	}

	/**
	 * 编辑方案时，加载方案信息数据
	 * @param planNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/loadNlifePlan")
	@ResponseBody
	public Map<String,Object> loadNlifePlan(HttpSession session, String planNo) throws Exception{
		GatewayUser user=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		Map<String, Object> map = nlifePlanConfigService.loadNlifePlan(planNo);
		/**分公司人员操作总公司方案*/
		if(!"'00'".equals(user.getDepartmentStr())){
			GatewayChannelInfo channleInfo=(GatewayChannelInfo)map.get("planChannelInfo");
			if("00".equals(channleInfo.getDeptCode())){
				map.put("isBanchs", true);
			}
		}
		String cancelTemplate =((NlifePlan)map.get("nlifePlan")).getCancelTemplate();
		if(!"".equals(cancelTemplate) && null != cancelTemplate){
			String cancelTemplate_val = tradSmsTemplateService.queryTradeByCode(cancelTemplate).getSmsTemplateText();
			map.put("cancelTemplate_val", cancelTemplate_val);
		}
		String messageTemplate =((NlifePlan)map.get("nlifePlan")).getMessageTemplate();
		if(!"".equals(messageTemplate) && null != messageTemplate){
			String messageTemplate_val = tradSmsTemplateService.queryTradeByCode(messageTemplate).getSmsTemplateText();
			map.put("messageTemplate_val", messageTemplate_val);
		}
		/**销售人员信息*/
		Map<String, String> salemap=new HashMap<String, String>();
		salemap.put("planCode", planNo);
		List<TradPlanSale> sales=tradPlanSaleService.queryTrade(salemap);
		if(sales!=null&&sales.size()>0){
			/**销售人员字典*/
			List<DictDto> dictDtos=DictCache.getDict("role_stype");
			map.put("sales", sales);
			for (TradPlanSale tradPlanSale : sales) {
				for (DictDto dictDto : dictDtos) {
					if(dictDto.getCode().equals(tradPlanSale.getPersonType())){
						tradPlanSale.setSaleTypeName(dictDto.getCodeName());
					}
				}
			}
		}
		return map;
	}
	/**
	 * 销售加载数据字典
	 * @param planNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/loadDic")
	@ResponseBody
	public Map<String,Object> loadDic() throws Exception{
		Map<String, Object> map = new HashMap<String,Object>();
		/**销售人员字典*/
		List<DictDto> dictDtos=DictCache.getDict(Constants.DICT_ROLE_STYPE);
		map.put("roleStype", dictDtos);
		return map;
	}

	/**
	 * 分页条件查询新意健险产品
	 * @param page
	 * @param nlifeProd
	 * @param startDateBegin
	 * @param startDateEnd
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryNlifeProdPageByCriteria")
	@ResponseBody
	public Page<NlifeProd> queryNlifeProdPageByCriteria(Page<NlifeProd> page, NlifeProd nlifeProd, String startDateBegin, String startDateEnd) throws Exception{

		Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
		paramMap.put("prodCode", nlifeProd.getProdCode()==null?"":nlifeProd.getProdCode());
		paramMap.put("prodName", nlifeProd.getProdName()==null?"":nlifeProd.getProdName());
		paramMap.put("startDateBegin", startDateBegin==null?"":startDateBegin);
		paramMap.put("startDateEnd", startDateEnd==null?"":startDateEnd);
		paramMap.put("status", "1");//1为有效产品

		page.setMap(paramMap);

		page = nlifePlanConfigService.queryNlifeProdPageByCriteria(page);
		return page;
	}

	/**
	 * 分页条件查询出单机构
	 * @param page
	 * @param dept
	 * @param partnerNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryDeptPageByCriteria")
	@ResponseBody
	public Page<CoreDept> queryDeptPageByCriteria(HttpSession session  ,Page<CoreDept> page, CoreDept dept, String partnerNo) throws Exception{
		page.setType(dept);
		page.setObj(partnerNo);
		page.setObj(session.getAttribute(Constants.SESSION_USER));
		page = nlifePlanConfigService.queryDeptPageByCriteria(page);

		return page;
	}

	/**
	 * 归属渠道-渠道类型-新业务来源处理(根据codeType和上级code从数据字典中查询下级级联信息)
	 * @param codeType
	 * @param parentCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/loadSubCascadeList")
	@ResponseBody
	public List<DictDto> loadSubCascadeList(DictDto dict) throws Exception {
		List<DictDto> list = nlifePlanConfigService.loadSubCascadeList(dict);
		return list;
	}

	/**
	 * 查询业务员-团队信息(从销管获取)
	 * @param COMCODE
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/querySauserAndTeamInfo")
	@ResponseBody
	public Result querySauserAndTeamInfo(String COMCODE) throws Exception {
		if(StrUtil.isEmpty(COMCODE)){
			return Result.error("出单机构不能为空");
		}

		Result result = null;
		try{
			result = nlifePlanConfigService.querySauserAndTeamInfo(COMCODE);
		}catch(Exception e){
			logger.info(e);
			return Result.error(e.getMessage());
		}
		return result;
	}

	/**
	 * 查询中介-协议信息(从销管获取)
	 * @param COMCODE
	 * @param TEAMCODE
	 * @param BUSINESSSOURCE
	 * @param CHANNELNAME
	 * @param PRODCODE
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryAgentAndAgreeInfo")
	@ResponseBody
	public Result queryAgentAndAgreeInfo(String COMCODE,String TEAMCODE,
										 String BUSINESSSOURCE,String CHANNELNAME,String PRODCODE) throws Exception {
		if(StrUtil.isEmpty(COMCODE)) return Result.error("出单机构不能为空");
		if(StrUtil.isEmpty(TEAMCODE)) return Result.error("团队代码不能为空");
		if(StrUtil.isEmpty(BUSINESSSOURCE)) return Result.error("业务来源不能为空");
		if(StrUtil.isEmpty(CHANNELNAME)) return Result.error("渠道名称不能为空");
		if(StrUtil.isEmpty(PRODCODE)) return Result.error("产品代码不能为空");

		Result result = null;
		try{
			result = nlifePlanConfigService.queryAgentAndAgreeInfo(COMCODE, TEAMCODE, BUSINESSSOURCE, CHANNELNAME, PRODCODE);
		}catch(Exception e){
			logger.info(e);
			return Result.error(e.getMessage());
		}
		return result;
	}

	/**
	 * 查询服务代码信息(从销管获取)
	 * @param COMCODE
	 * @param BUSINESSSOURCE
	 * @param CHANNELNAME
	 * @param USERCODE
	 * @param AGENTCODE
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryServiceNo")
	@ResponseBody
	public Result queryServiceNo(String COMCODE,String BUSINESSSOURCE,
								 String CHANNELNAME,String USERCODE,String AGENTCODE) throws Exception {
		if(StrUtil.isEmpty(COMCODE)) return Result.error("出单机构不能为空");
		if(StrUtil.isEmpty(BUSINESSSOURCE)) return Result.error("业务来源不能为空");
		if(StrUtil.isEmpty(CHANNELNAME)) return Result.error("渠道名称不能为空");
		if(StrUtil.isEmpty(USERCODE)) return Result.error("业务员代码不能为空");

		Result result = null;
		try{
			result = nlifePlanConfigService.queryServiceNo(COMCODE, BUSINESSSOURCE, CHANNELNAME, USERCODE, AGENTCODE);
		}catch(Exception e){
			logger.info(e);
			return Result.error(e.getMessage());
		}
		return result;
	}

	/**
	 * 新增方案
	 * @param nlifeProd
	 * @param nlifePlan
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/addOrUpdateNlifePlan")
	@ResponseBody
	public Result addOrUpdateNlifePlan(String channelFlag,String planType,String saleArry,NlifePlan nlifePlan,String oldPlanNo,String oldPartnerNo,String oldAgentType,String updateSpecialArran) throws Exception{
		String planName = nlifePlan.getPlanName();
		if(StrUtil.isEmpty(planName)) return Result.error("投保方案名称不能为空");

		String prodCode = nlifePlan.getProdCode();
		if(StrUtil.isEmpty(prodCode)) return Result.error("产品编号不能为空");

		String partnerNo = nlifePlan.getPartnerNo();
		if(StrUtil.isEmpty(partnerNo)) return Result.error("合作伙伴代码不能为空");
		nlifePlan.setCancelTemplate(URLDecoder.decode(nlifePlan.getCancelTemplate(), "UTF-8"));
		//1、合作伙伴代理3、个人代理4、总对总代理
		NlifeProd nlifeProd = nlifeProdDao.queryProdInfoById(nlifePlan.getProdCode());
		String agentType = nlifePlan.getAgentType();
		String dptCde = nlifePlan.getDptCde();
		if("1".equals(agentType)&&!"1".equals(channelFlag)){
			if(StrUtil.isEmpty(dptCde)) return Result.error("出单机构不能为空");
		}
		if(updateSpecialArran != null){
			//对升级特约进行处理，形如 special2=xxxx；special3=xxxxx；......
			String[]strs =  updateSpecialArran.split(";");
			List<Map<String,String>> param = new ArrayList<Map<String,String>>();
			if(strs.length > 0){
				for(String str:strs){
					Map<String,String> map = new HashMap<String, String>();
					//每个str 都是一个key=value的对
					String key = str.split("=")[0];
					String value = str.split("=")[1];
					if(key != null && key.length() > "specialArran".length()){
						map.put("prodCode", prodCode);
						map.put("hookproduct", key.substring("specialArran".length()));
						map.put("spicalArran", value);
					}
					param.add(map);
				}
				nlifeProdDao.updateUpdateProdSpecialArran(param);
			}
		}
		BigDecimal commRate = nlifePlan.getCommRate();
		if(!"2".equals(nlifePlan.getAgentFeeConfig())){}
		NlifeProd np = nlifeProdDao.queryProdInfoById(nlifePlan.getProdCode());
		//1、合作伙伴代理3、个人代理4、总对总代理
		String empNo = nlifePlan.getEmpNo();
		String teamCode = nlifePlan.getTeamCode();
		String teamName = nlifePlan.getTeamName();
		String categoryCode = nlifePlan.getCategoryCode();
		String agentNo = nlifePlan.getAgentNo();
		String agentName = nlifePlan.getAgentName();
		String protocolNo = nlifePlan.getProtocolNo();
		String serviceCode = nlifePlan.getServiceCode();
		//合作伙伴代理时校验销售渠道信息是否有效
		if("1".equals(agentType) && !"1".equals(channelFlag)) {
			Map<String,String> map = new HashMap<String, String>();
			SimpleDateFormat dateformat = new SimpleDateFormat("0000yyyyMMddHHmmss");
			String SERIALDECIMAL = dateformat.format(System.currentTimeMillis());
		}
		String isEpolicy = nlifePlan.getIsEpolicy();
		//是否打印单证
		String isPrintCard = nlifePlan.getIsPrintCard();
		String cardType = nlifePlan.getCardType();
		nlifePlan.setCancelTemplate(URLDecoder.decode(nlifePlan.getCancelTemplate(), "UTF-8"));
		String selectAccessorylistStr = nlifePlan.getSelAccessory();
		String ids="";
		if(!StrUtil.isEmpty(selectAccessorylistStr)){
			//创建一个JsonPaser
			JsonParser jsonParser=new JsonParser();
			//通过JsonPaser对象可以把字符串解析成一个JsonElement对象
			JsonElement element=jsonParser.parse(selectAccessorylistStr);
			//把JsonElement转化成jsonArray
			JsonArray jsonArray=null;
			//判断element是不是jsonArray
			if(element.isJsonArray()){
				jsonArray=element.getAsJsonArray();
			}
			//循环得到id的拼接字符串
			for (JsonElement jsonElement : jsonArray) {
				if(jsonElement.getAsJsonObject().get("id")!=null){
					String id=jsonElement.getAsJsonObject().get("id").getAsString();
					ids=ids+id+",";
				}
			}
			//如果长度不为0.去除，
			if(ids.length()>0){
				ids=ids.substring(0, ids.length()-1);
			}
		}
		nlifePlan.setSelAccessory(ids);

		String planNo = nlifePlan.getPlanNo();
		Result result = null;
		if(StrUtil.isEmpty(planNo)){
			if(StrUtil.isEmpty(oldPlanNo)){//新增
				result = nlifePlanConfigService.addNlifePlan(nlifePlan,nlifeProd,channelFlag);
			}else{//复制新增
				result = nlifePlanConfigService.copyAddNlifePlan(oldPlanNo,oldPartnerNo,oldAgentType,nlifePlan,nlifeProd,channelFlag);
			}
			//判断是否出单机构是否是广东分公司
			if(StrUtil.isNotEmpty(dptCde)){
				if(dptCde.startsWith("44")){
					addTradSale(nlifePlan.getPlanNo(), planType, saleArry);
				}
			}
		}else{
			result = nlifePlanConfigService.updateNlifePlan(nlifePlan,nlifeProd);
		}
		return result;
	}
	/**
	 * 加载方案关联个人代理、总对总代理信息、联合出单代理信息
	 * @param page
	 * @param planNo
	 * @param agentType
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryAgentInfoRelaPageByCriteria")
	@ResponseBody
	public Page<Map<String,Object>> queryAgentInfoRelaPageByCriteria(Page<Map<String,Object>> page,
																	 String planNo,String agentType,HttpSession session) throws Exception{
		if(StrUtil.isEmpty(planNo)){
			page.setResult("planNo不能为空");
			return page;
		}
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		if(!("3".equals(agentType) || "4".equals(agentType)  || "5".equals(agentType)||"6".equals(agentType)||"7".equals(agentType))){
			page.setResult("agentType取值有误");
			return page;
		}
		NlifePlan nlifePlan = nlifePlanDao.queryById(planNo);
		Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
		paramMap.put("planNo", planNo);
		paramMap.put("parentChannelCode", nlifePlan.getPartnerNo());
		if("4".equals(agentType)){
			paramMap.put("deptCodeStr", gatewayuser.getDepartmentStr());
		}
		page.setMap(paramMap);
		page = nlifePlanConfigService.queryAgentInfoRelaPageByCriteria(page,agentType);

		return page;
	}
	/**
	 * 跟单配置信息，与方案关联保存
	 * @param page
	 * @param planNo
	 * @param agentType
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveCoinPlan")
	@ResponseBody
	public Map<String,Object> saveCoinPlan(CoinPlanConfig coin) throws Exception{
		Map<String, Object> map=new HashMap<String, Object>();
		try {
			if(coinPlanConfigService.saveCoinPlan(coin)){
				map.put("success", true);
			}else{
				map.put("success", false);
			}
		} catch (Exception e) {
			map.put("success", false);
			logger.info("数据库操作错误",e);
		}
		return map;
	}

	/**
	 * 加载个人代理、总对总代理信息、联合出单代理信息
	 * @param page
	 * @param planNo
	 * @param agentType
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryAgentInfoPageByCriteria")
	@ResponseBody
	public Page<Map<String,Object>> queryAgentInfoPageByCriteria(HttpSession session,Page<Map<String,Object>> page, String planNo, String partnerNo, String agentType,
																 String confStatus, String userCode, String userName, String branch, String branchName , String key1,
																 String key2 , String key3, String key4 , String key5,String unionType,String deptId,String deptName) throws Exception{
		if(StrUtil.isEmpty(planNo)){
			page.setResult("planNo不能为空");
			return page;
		}
		if(StrUtil.isEmpty(partnerNo)&&!"5".equals(agentType)){
			page.setResult("partnerNo不能为空");
			return page;
		}
		if(!("3".equals(agentType) || "4".equals(agentType) || "5".equals(agentType)||"7".equals(agentType))){
			page.setResult("agentType取值有误");
			return page;
		}
		//登陆用户
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
		paramMap.put("planNo", planNo);
		paramMap.put("partnerNo", partnerNo);
		paramMap.put("agentType", agentType);
		paramMap.put("confStatus", confStatus);
		paramMap.put("userCode", userCode);
		paramMap.put("userName", userName);
		paramMap.put("branch", branch);
		paramMap.put("branchName", branchName);
		paramMap.put("key1", key1);
		paramMap.put("key2", key2);
		paramMap.put("key3", key3);
		paramMap.put("key4", key4);
		paramMap.put("key5", key5);
		paramMap.put("unionType", unionType);

		paramMap.put("deptId", deptId);//查询条件中的出单机构代码
		paramMap.put("deptName", deptName);//查询条件中的出单机构名称
		paramMap.put("dept_code",gatewayuser.getDepartmentStr().substring(1, 3));//登陆用户出单机构（两位）
		/**总对总分公司权限*/
		paramMap.put("dept_code4",gatewayuser.getDepartmentStr());
		page.setMap(paramMap);

		page = nlifePlanConfigService.queryAgentInfoPageByCriteria(page,agentType);

		return page;
	}

	/**
	 * 更新方案关联的个人代理信息
	 * @param session
	 * @param planNo
	 * @param isPrintCard
	 * @param agentInfoListStr
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/updateAgentInfoRela")
	@ResponseBody
	public Result updateAgentInfoRela(HttpSession session,String planNo, String isPrintCard, String agentInfoListStr,String agentType) throws Exception{
		GatewayUser user=(GatewayUser) session.getAttribute(Constants.SESSION_USER);

		if(StrUtil.isEmpty(planNo)){ return Result.error("方案号不能为空"); }
		if(StrUtil.isEmpty(agentInfoListStr)){ return Result.error("代理信息不能为空"); }
		List<String> list=new ArrayList<String>();

		//创建一个JsonParser
		JsonParser jsonParser = new JsonParser();
		//通过JsonParser对象可以把json格式的字符串解析成一个JsonElement对象
		JsonElement jsonElement = jsonParser.parse(agentInfoListStr);
		//把JsonElement对象转换成JsonArray
		JsonArray jsonArray = null;
		if(jsonElement.isJsonArray()){
			jsonArray = jsonElement.getAsJsonArray();
		}else{
			return Result.error("无效的代理信息");
		}
		for (JsonElement je : jsonArray) {
			if(je.getAsJsonObject().get("id")==null){
				continue;
			}
			String id =je.getAsJsonObject().get("id").getAsString();
			if("Y".equals(isPrintCard)){
				String cardapplicant=je.getAsJsonObject().get("cardapplicant").getAsString();
				if(StrUtil.isEmpty(id)||StrUtil.isEmpty(cardapplicant)){
					return Result.error("您配置的代理信息中存在单证领用人为空的,单证领用人不能为空");
				}
			}
			if(je.getAsJsonObject().get("branch")!=null){
				String branch=je.getAsJsonObject().get("branch").getAsString();
				/**广东销售信息*/
				if(StrUtil.isNotEmpty(branch)&&branch.startsWith("44")){
					list.add(id);
				}
			};

		}

		Result result = nlifePlanConfigService.updateAgentInfoRela(agentType,list,user.getUserid(), planNo, agentInfoListStr);

		return result;
	}
	/***
	 * 销售信息保存
	 */
	@RequestMapping(value = "/addTradPlanSale")
	@ResponseBody
	public Result addTradPlanSale(String planCode,String planType,String saleArry) throws Exception {
		return addTradSale(planCode, planType, saleArry);
	}
	private Result addTradSale(String planCode,String planType,String saleArry) throws Exception{
		Result result = null;
		if(planCode!=null&&!"".equals(planCode)){
			Map<String, String> map=new HashMap<String, String>();
			map.put("planCode", planCode);
			tradPlanSaleService.deleteTrade(map);
			List<Map<String,String>> list = JsonUtils.parseJson(saleArry, ArrayList.class);
			List<TradPlanSale> planSales=new ArrayList<TradPlanSale>();
			for (Map<String, String> map2 : list) {
				TradPlanSale planSale=new TradPlanSale();
				planSale.setAgentFee((Double.parseDouble(map2.get("costRate"))));
				planSale.setSeqNo(map2.get("seqNo"));
				planSale.setAgentCode(map2.get("agentCode"));
				planSale.setAgentName(map2.get("agentName"));
				planSale.setEmpNo(map2.get("salePerson"));
				planSale.setPersonType(map2.get("saleType"));
				planSale.setSaleName(map2.get("saleName"));
				planSale.setPracticeNo(map2.get("permitNo"));
				planSale.setPlanNo(planCode);
				planSale.setInsertDate(new Date());
				planSale.setPlanType(planType);
				planSales.add(planSale);
			}
			Boolean flag=tradPlanSaleService.addTrade(planSales);
			if(flag){
				//清除缓存
				gatewayClearCacheManager.clearNlifeCacheInfoManager();
				result=Result.success("添加成功");
			}else{
				result=Result.error("添加失败");
			}
		}else{
			result=Result.error("方案号为空");
		}
		return result;

	}
	@RequestMapping(value = "/dowloadPlan")
	public void dowloadPlan(String planNo,HttpSession session,HttpServletResponse response,HttpServletRequest request) throws Exception {
		ServletOutputStream outPutStream=null;

		/**浏览器处理*/
		final String userAgent = request.getHeader("USER-AGENT");
		logger.info("使用的浏览器"+userAgent);
		try{
			String  fileName="新意见险方案sql.txt";
			if(userAgent.indexOf( "MSIE")!=-1){
				/**ie浏览器*/
				fileName=java.net.URLEncoder.encode(fileName,"UTF-8");
			}else if(userAgent.indexOf( "Mozilla")!=-1){
				/**火狐浏览器*/
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			}else{
				/**其他浏览器*/
				fileName=java.net.URLEncoder.encode(fileName,"UTF-8");
			}
			String[] planNos=forPlans(planNo);
			System.out.println(planNos);
			Map<String, Object> map=queryNlife(planNos);
			/**查询产品信息*/
			response.setContentType("text/plain");
			response.setHeader("Content-disposition","attachment; filename="+fileName);
			outPutStream=response.getOutputStream();
			String ss=FreeMarkerUtil.process("nlifePlan.ftl", map);
			outPutStream.write(ss.getBytes());
			outPutStream.flush();
		}catch(IOException e){
			logger.info("创建文件出错",e);
		}finally{
			if(outPutStream!=null){
				outPutStream.close();
			}
		}
	}
	/**产品导出数据处理
	 * @throws Exception **/
	private Map<String, Object> queryNlife(String[] plans) throws Exception{
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("plans", plans);
		List<String> planSqls=new ArrayList<String>();
		List<String> groupSqls=new ArrayList<String>();
		List<String> infoSqls=new ArrayList<String>();
		List<String> subSqls=new ArrayList<String>();
		List<String> agentSqls=new ArrayList<String>();
		List<String> saleSqls=new ArrayList<String>();
		List<String> coinSqls=new ArrayList<String>();
		List<String> coinFeeSqls=new ArrayList<String>();
		List<String> saleConfigSqls=new ArrayList<String>();
		/**导出方案*/
		List<Map<String, Object>> nlifeplans= nlifePlanConfigService.impNlifePlan(map);
		for (Map<String, Object> map2 : nlifeplans) {
			String agent_type =(String) map2.get("AGENT_TYPE");
			if("1".equals(agent_type)){
				map2.put("STATE","0");
				map2.put("CHECK_STATUS","未审核");
				map2.put("IS_PUSHED_SALES_INFO","N");
			}
			String sql=getInsertSql(map2, "T_NLIFE_PLAN");
			planSqls.add(sql);
		}
		/**导出方案组*/
		List<Map<String, Object>> groups= insuPlanGroupService.impNlifeGroup1(map);
		for (Map<String, Object> map2 : groups) {
			String sql=getInsertSql(map2, "T_TRAD_INSU_PLAN_GROUP");
			groupSqls.add(sql);
		}
		/**代理信息*/
		List<Map<String, Object>> infos=nlifePlanConfigService.impNlifeInfo(map);
		for (Map<String, Object> map2 : infos) {
			String sql=getInsertSql(map2, "T_TRAD_AGENT_INFO");
			infoSqls.add(sql);
		}

		/**查询网点信息**/
		List<Map<String, Object>> subs=subChannelService.impNlifeSub(map);
		for (Map<String, Object> map2 : subs) {
			String sql=getInsertSql(map2, "T_GATEWAY_SUB_CHANNEL");
			subSqls.add(sql);
		}
		/**导出方案代理关联信息*/
		List<Map<String, Object>> agents=  nlifePlanConfigService.impNlifeRela(map);
		for (Map<String, Object> map2 : agents) {
			String sql=getInsertSql(map2, "T_TRAD_AGENT_INFO_RELA");
			agentSqls.add(sql);
		}
		/**广东销售*/
		List<Map<String, Object>> sales= tradPlanSaleService.impNlifeSale(map);
		for (Map<String, Object> map2 : sales) {
			String sql=getInsertSql(map2, "T_TRAD_PLAN_SALE");
			saleSqls.add(sql);
		}
		/**费用跟单方案关联**/
		List<Map<String, Object>>  coins=coinPlanConfigService.implCoinPlan(map); //跟单配置关联
		for (Map<String, Object> map2 : coins) {
			String sql=getInsertSql(map2, "COIN_PLAN_CONFIG");
			coinSqls.add(sql);
		}
		/**费用跟单三费*/
		List<Map<String, Object>>  coinFees=coinFeeConfigService.implCoinFee(map); //共享保三费配置
		for (Map<String, Object> map2 : coinFees) {
			String sql=getInsertSql(map2, "COIN_FEE_CONFIG");
			coinFeeSqls.add(sql);
		}
		/**费用跟单*/
		List<Map<String, Object>>  saleConfig=saleConfigService.implSaleConfigs(map); //跟单费用配置
		for (Map<String, Object> map2 : saleConfig) {
			String sql=getInsertSql(map2, "SALE_FEE_CONFIG");
			saleConfigSqls.add(sql);
		}
		map.put("plans",planSqls );
		map.put("groups", groupSqls);
		map.put("agents", agentSqls);
		map.put("infos", infoSqls);
		map.put("subs", subSqls);
		map.put("sales", saleSqls);
		map.put("coinPlanConfigsList", coinSqls);
		map.put("coinFeeConfigsList", coinFeeSqls);
		map.put("saleConfigsList", saleConfigSqls);
		return map;
	}
	/**循环map返回insert语句
	 * @throws Exception **/
	private String getInsertSql(Map<String, Object> map,String table) throws Exception{
		String sql="INSERT INTO " +table;
		String cloum=" (";
		String value=" (";
		if(map!=null){
			for (String key : map.keySet()) {
				if(key.equalsIgnoreCase("prod_code")){
					continue;
				}
				if("T_TRAD_AGENT_INFO_RELA".equalsIgnoreCase(table)&&key.startsWith("INFO_")){
					continue;
				}
				if(key.equalsIgnoreCase("prodCode")){
					cloum+="PROD_CODE,";
					value+="'"+map.get(key)+"',";
					continue;
				}
				if(key.equalsIgnoreCase("plan_group_id")){
					cloum+=key+",";
					value+="(SELECT TRAD.GROUP_ID  FROM T_TRAD_PLAN_GROUP  TRAD   LEFT JOIN T_NLIFE_PROD PROD ON  TRAD.PROD_TYPE=PROD.PROD_TYPE  LEFT JOIN T_NLIFE_PLAN  PLAN ON PLAN.PROD_CODE=PROD.PROD_CODE  WHERE PLAN.PLAN_NO='"+map.get("INSU_PLAN_NO")+"' AND TRAD.IS_PROD_GROUP='1'),";
					continue;
				}
				if(key.equalsIgnoreCase("id")&&(table.equalsIgnoreCase("t_trad_agent_info")||table.equalsIgnoreCase("t_trad_agent_info_rela"))){
					cloum+=key+",";
					String seq="S_"+table+".NEXTVAL ,";
					value+=seq.replace("T_TRAD", "TRAD");
					continue;
				}
				if(key.equalsIgnoreCase("AGENT_INFO_ID")){
					cloum+=key+",";
					String sql1="(SELECT ID FROM T_TRAD_AGENT_INFO INFO WHERE  1=1 AND";
					if("3".equals(map.get("INFO_AGENT_TYPE"))){
						sql1+="  INFO.CHANNEL_CODE='"+map.get("INFO_CHANNEL_CODE")+"'AND INFO.USER_CODE='"+map.get("INFO_USER_CODE")+"' ) ,";
						value+=sql1;
					}
					if("4".equals(map.get("INFO_AGENT_TYPE"))){
						sql1+=" INFO.CHANNEL_CODE='"+map.get("INFO_CHANNEL_CODE")+"'AND INFO.SUB_CHANNEL_CODE='"+map.get("INFO_SUB_CHANNEL_CODE")+"' ) ,";
						value+=sql1;
					}
					if("5".equals(map.get("INFO_AGENT_TYPE"))){
						for (int i = 1; i < 6; i++) {
							if(map.get("KEY"+i)!=null){
								sql1+=" AND INFO.KEY"+i+"= "+map.get("INFO_KEY"+i)+",";
							}
						}
						value+=sql1;
					}
					continue;
				}
				if(key.equalsIgnoreCase("id")){
					cloum+=key+",";
					value+="(SELECT MAX("+key+")+1  from "+table+") ,";
					continue;
				}
				if(key.equalsIgnoreCase("SPECIAL_ARRAN")&&map.get(key)!=null){
					cloum+=key+",";
					value+="'"+StrUtil.ClobToString((Clob) map.get(key))+"',";
					continue;
				}
				if(key.equalsIgnoreCase("oper_time")||key.equalsIgnoreCase("INSERT_TIME")||key.equalsIgnoreCase("UPDATE_TIME")||key.equalsIgnoreCase("OPRATE_TIME")){
					cloum+=key+",";
					value+="SYSDATE,";
					continue;
				}
				cloum+=key+",";
				if(map.get(key)!=null){
					value+="'"+map.get(key)+"',";
				}else{
					value+=map.get(key)+",";
				}

			}
			cloum=cloum.substring(0,cloum.length()-1)+" )";
			value=value.substring(0,value.length()-1)+" )";
		}
		return sql+cloum+" VALUES "+value;
	}
	/**产品号处理*/
	private String[] forPlans(String planNo){
		if(StrUtil.isEmpty(planNo)){
			return null;
		}
		String[] strs=planNo.split(",");
		return strs;
	}

	/**
	 * 总对总区域列表
	 * @param page
	 * @param planNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryAgentInfoZon4PageByCriteria")
	@ResponseBody
	public Page<Map<String,Object>> queryAgentInfoZon4PageByCriteria(Page<Map<String,Object>> page, String planNo, String partnerNo, String isFlag,
																	 String branchName) throws Exception{
		if(StrUtil.isEmpty(planNo)){
			page.setResult("planNo不能为空");
			return page;
		}

		Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
		paramMap.put("planNo", planNo);
		paramMap.put("partnerNo", partnerNo);
		if(StrUtil.isNotEmpty(branchName)){
			paramMap.put("deptAbr", "%"+branchName+"%");
		}else{
			paramMap.put("deptAbr", null);
		}
		if(StrUtil.isEmpty(isFlag)){
			paramMap.put("isFlag", null);
		}else{
			paramMap.put("isFlag", isFlag);

		}
		page.setMap(paramMap);

		page = nlifePlanConfigService.queryAgentInfoZon4PageByCriteria(page);

		return page;
	}

	/**
	 * 联合出单区域列表
	 * @param page
	 * @param planNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryAgentInfoZon5PageByCriteria")
	@ResponseBody
	public Page<Map<String,Object>> queryAgentInfoZon5PageByCriteria(Page<Map<String,Object>> page, String planNo, String partnerNo, String isFlag,String branchName) throws Exception{
		if(StrUtil.isEmpty(planNo)){
			page.setResult("planNo不能为空");
			return page;
		}

		Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
		paramMap.put("planNo", planNo);
		paramMap.put("partnerNo", partnerNo);
		if(StrUtil.isNotEmpty(branchName)){
			paramMap.put("deptAbr", "%"+branchName+"%");
		}else{
			paramMap.put("deptAbr", null);
		}
		if(StrUtil.isEmpty(isFlag)){
			paramMap.put("isFlag", null);
		}else{
			paramMap.put("isFlag", isFlag);

		}
		page.setMap(paramMap);

		page = nlifePlanConfigService.queryAgentInfoZon5PageByCriteria(page);

		return page;
	}
	/***
	 * 方案配置保存
	 */
	@RequestMapping(value = "/updateZon4Config")
	@ResponseBody
	public Result updateZon4Config(HttpSession session,String zonListStr,String branchs,String partnerNo,String planNo) throws Exception {
		try {
			GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);

			return addTradPlan(zonListStr, planNo,branchs,partnerNo,gatewayuser.getUserid());
		} catch (Exception e) {
			logger.info(e);
			return Result.error("数据库错误");
		}
	}
	/***
	 * 方案配置清除
	 */
	@RequestMapping(value = "/clearAgentInfoZon4Div")
	@ResponseBody
	public Result clearAgentInfoZon4Div(String zonListStr,String branchs,String partnerNo,String planNo) throws Exception {
		Result result = null;
		try {
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("planNo", planNo);
			map.put("branchs", strToList(branchs));
			map.put("partnerNo", partnerNo);
			/**删除合作伙伴，机构下已关联的代理信息*/
			nlifePlanConfigService.delZonTradInfo(map);
			result=Result.success("清除成功");
		} catch (Exception e) {
			logger.info(e);
			result=Result.error("清除失败");
		}
		return result;
	}
	/**参数处理*/
	private String[] strToList(String branchs){
		if(StrUtil.isNotEmpty(branchs)){
			return branchs.split(",");
		}
		return null;
	}
	private Result addTradPlan(String zonListStr,String planNo,String branchs,String partnerNo,Long userCode) throws Exception{
		Result result = null;
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("planNo", planNo);
		map.put("branchs", strToList(branchs));/**已配置的机构branchs*/
		map.put("partnerNo", partnerNo);
		try {
			/**删除合作伙伴，机构下已关联的代理信息*/
			if(StrUtil.isNotEmpty(zonListStr)){
				List<Map<String,String>> list = JsonUtils.parseJson(zonListStr, ArrayList.class);
				List<TradAgentInfoRela> tradAgentInfoRelas=new ArrayList<TradAgentInfoRela>();
				boolean is44=false;
				/**参数处理*/
				if(list!=null&&list.size()>0){
					for (Map<String, String> map2 : list) {
						TradAgentInfoRela planSale=new TradAgentInfoRela();
						if(null!=map2.get("businessRate")&&StrUtil.isNotEmpty(String.valueOf(map2.get("businessRate")))){
							planSale.setBusiness(new BigDecimal(String.valueOf(map2.get("businessRate"))));
						}
						if(null!=map2.get("commRate")&&StrUtil.isNotEmpty(String.valueOf(map2.get("commRate")))){
							planSale.setCommRate(new BigDecimal(String.valueOf(map2.get("commRate"))));
						}
						if(null!=map2.get("marketRate")&&StrUtil.isNotEmpty(String.valueOf(map2.get("marketRate")))){
							planSale.setMarket(new BigDecimal(String.valueOf(map2.get("marketRate"))));
						}
						planSale.setOperUser(userCode);
						planSale.setInsuPlanNo(planNo);
						planSale.setOperTime(new Date());
						planSale.setChannelCode(partnerNo);
						String deptCode=map2.get("branch");
						planSale.setDeptCode(deptCode+"%");
						if("44".equals(deptCode)){
							is44=true;
						}
						tradAgentInfoRelas.add(planSale);
					}
				}
				result=nlifePlanConfigService.addZonTradInfo(tradAgentInfoRelas,map,is44);
			}
		} catch (Exception e) {
			logger.info(e);
			result=Result.error("配置失败");
		}
		return result;
	}
	/**
	 * 查询电子邮件模板列表
	 */
	@RequestMapping(value = "/queryEmailTempList")
	@ResponseBody
	public Map<String,Object> queryEmailTempList() throws Exception{
		Map<String, Object> map=new HashMap<String, Object>();
		List<TradEmailTemplate> emailTemplates=tradEmailTemplateService.queryEmailTemplate();
		map.put("templates", emailTemplates);
		return map;
	}

	/***
	 * 方案配置保存
	 */
	@RequestMapping(value = "/updateZon5Config")
	@ResponseBody
	public Result updateZon5Config(HttpSession session,String zonListStr,String branchs,String partnerNo,String planNo) throws Exception {
		try {
			GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);

			return addTradPlan5(zonListStr, planNo,branchs,partnerNo,gatewayuser.getUserid());
		} catch (Exception e) {
			logger.info(e);
			return Result.error("数据库错误");
		}
	}

	private Result addTradPlan5(String zonListStr,String planNo,String branchs,String partnerNo,Long userCode) throws Exception{
		Result result = null;
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("planNo", planNo);
		map.put("branchs", strToList(branchs));/**已配置的机构branchs*/
		map.put("partnerNo", partnerNo);
		try {
			/**删除合作伙伴，机构下已关联的代理信息*/
			if(StrUtil.isNotEmpty(zonListStr)){
				List<Map<String,String>> list = JsonUtils.parseJson(zonListStr, ArrayList.class);
				List<TradAgentInfoRela> tradAgentInfoRelas=new ArrayList<TradAgentInfoRela>();
				boolean is44=false;
				/**参数处理*/
				if(list!=null&&list.size()>0){
					for (Map<String, String> map2 : list) {
						TradAgentInfoRela planSale=new TradAgentInfoRela();
						if(null!=map2.get("businessRate")&&StrUtil.isNotEmpty(String.valueOf(map2.get("businessRate")))){
							planSale.setBusiness(new BigDecimal(String.valueOf(map2.get("businessRate"))));
						}
						if(null!=map2.get("commRate")&&StrUtil.isNotEmpty(String.valueOf(map2.get("commRate")))){
							planSale.setCommRate(new BigDecimal(String.valueOf(map2.get("commRate"))));
						}
						if(null!=map2.get("marketRate")&&StrUtil.isNotEmpty(String.valueOf(map2.get("marketRate")))){
							planSale.setMarket(new BigDecimal(String.valueOf(map2.get("marketRate"))));
						}
						planSale.setOperUser(userCode);
						planSale.setInsuPlanNo(planNo);
						planSale.setOperTime(new Date());
						planSale.setChannelCode(partnerNo);
						String deptCode=map2.get("branch");
						planSale.setDeptCode(deptCode+"%");
						if("44".equals(deptCode)){
							is44=true;
						}
						tradAgentInfoRelas.add(planSale);
					}
				}
				result=nlifePlanConfigService.addZonTradInfo5(tradAgentInfoRelas,map,is44);
			}
		} catch (Exception e) {
			logger.info(e);
			result=Result.error("配置失败");
		}
		return result;
	}
	/***
	 * 方案配置清除
	 */
	@RequestMapping(value = "/clearAgentInfoZon5Div")
	@ResponseBody
	public Result clearAgentInfoZon5Div(String zonListStr,String branchs,String partnerNo,String planNo) throws Exception {
		Result result = null;
		try {
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("planNo", planNo);
			map.put("branchs", strToList(branchs));
			map.put("partnerNo", partnerNo);
			/**删除合作伙伴，机构下已关联的代理信息*/
			nlifePlanConfigService.delZonTradInfo5(map);
			result=Result.success("清除成功");
		} catch (Exception e) {
			logger.info(e);
			result=Result.error("清除失败");
		}
		return result;
	}



	/**
	 * 分页条件查询健康告知
	 * @param session
	 * @param page
	 * @param Map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/loadNlifeHealthInform")
	@ResponseBody
	public Page<Map<String,Object>> loadNlifeHealthInform(HttpSession session,Page<Map<String,Object>> page ,String healthInformName , String prodName , String prodCode) throws Exception{


		Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
		paramMap.put("coreProdName", prodName == null ? "" : prodName );
		paramMap.put("coreProdCode", prodCode == null ? "" : prodCode);
		paramMap.put("healthInformName", healthInformName == null ? "" : healthInformName);

		page.setMap(paramMap);
		page = nlifePlanConfigService.loadNlifeHealthInform(page);
		return page;
	}

	//跳转新增健康告知页面
	@RequestMapping(value = "/toAddNewHealthInform")
	public String toAddNewHealthInform(ModelMap model){
		return "nlifeProduct/planConfig/addHealthInform";
	}


	//导入健康告知前查一下是否已存在
	@RequestMapping(value = "/isHealthInformExist")
	@ResponseBody
	public Page<Map<String,String>> isHealthInformExist(String coreProdCode,ModelMap model,HttpServletRequest request , HttpSession session ) throws Exception{
		boolean rs = nlifePlanConfigService.isHealthInformExist(coreProdCode);
		Page<Map<String,String>> page = new Page<Map<String,String>>();
		if(rs){
			page.setResult("warning");
		}else{
			page.setResult("success");
		}
		return page;
	}


	/**
	 * word上传
	 */
	@RequestMapping(value = "/HealthinformUpload")
	public void riskFileUpload(@RequestParam MultipartFile[] myfiles,HttpServletResponse response, HttpSession session,String coreProdCode , String healthInformName ) throws Exception {
		//设置编码格式
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");

		PrintWriter out = null;
		List<InputStream> inputStreams = null;
		Page<String>  page = new Page<String>();
		try {
			//获取writer对象。
			out = response.getWriter();
			if (myfiles.length < 1) {
				//当myfiles长度小于1，上传为空，返回报错信息
				page.setResult("error");
				page.setMessage("请添加上传文件!");
			}else{
				inputStreams=nlifePlanConfigService.getFileInputStream(myfiles, coreProdCode , healthInformName);
				logger.info("读写成功");
				page.setResult("success");
				page.setMessage((String)session.getAttribute("result"));
			}
		} catch (Exception e) {
			logger.info("---------读取文件失败---------",e);
			page.setResult("error");
			page.setMessage(e.getMessage());
		} finally {
			if(null!=inputStreams){
				for (InputStream input:inputStreams){
					try{
						input.close();
					}catch(Exception e){
						logger.warn("关闭流失败！", e);
					}
				}
			}
			out.write(JsonUtils.toJson(page));
			try {
				out.close();
			} catch (Exception e) {
				logger.warn("关闭流失败！", e);
			}
		}
	}



	/*删除已经存在的健康告知*/
	@RequestMapping(value = "delNlifeHealthInform")
	public Page<Map<String,String>> delNlifeHealthInform(String id){
		Page<Map<String,String>> page  = new Page<Map<String,String>>();
		try{
			nlifePlanConfigService.delNlifeHealthInform(id);
			page.setResult("success");
		}catch (Exception e ){
			page.setResult("error");
			page.setMessage("删除失败，请联系管理！");
		}

		return page;
	}
	//三费校验
	public String checkIfSaveNlifePlan(NlifeProd prod,String prodCode,String agent_type,BigDecimal commRate, BigDecimal marketPreserveRate,BigDecimal businessPerformanceRate,String agentFeeConfig) throws Exception{
		String str="";
		NlifeCoreRisk ncr= nlifePlanConfigService.queryMainRiskOrFirstRisk(prodCode);
		String singleOrGroup = prod.getAppType();//0 个单，1 团单
		String unit = prod.getPppUnit();//保险期限单位，y 年，m 月，d 天，h 时
		Long maxTime = prod.getMaxDays();
		//条款比例上限
		BigDecimal riskToplimit = new BigDecimal(0);
		String clauseType = ncr.getClauseType(); //条款类型：1为借款人意外险，2为建工意外险
		if(null!=ncr.getOneYearSingle()&&null!=ncr.getMoreYearSingle()&&null!=ncr.getOneYearGroup()&&null!=ncr.getMoreYearGroup()&&null!=commRate&&null!=marketPreserveRate&&null!=businessPerformanceRate){
			if("0".equalsIgnoreCase(singleOrGroup)) {//个单
				if ("1".equals(clauseType) || "2".equals(clauseType)){
					//条款类型为借款人或者建工意外险时
					riskToplimit = ncr.getOneYearSingle();
				}else {
					if ("y".equalsIgnoreCase(unit)) {
						if (maxTime > 1) {
							riskToplimit = ncr.getMoreYearSingle();
						}else{
							riskToplimit = ncr.getOneYearSingle();
						}
					}
					if ("m".equalsIgnoreCase(unit)) {
						if (maxTime > 12) {
							riskToplimit = ncr.getMoreYearSingle();
						}else{
							riskToplimit = ncr.getOneYearSingle();
						}
					}
					if ("d".equalsIgnoreCase(unit)) {
						if (maxTime > 365) {
							riskToplimit = ncr.getMoreYearSingle();
						}else{
							riskToplimit = ncr.getOneYearSingle();
						}
					}
					if ("h".equalsIgnoreCase(unit)) {
						if (maxTime > 8760) {
							riskToplimit = ncr.getMoreYearSingle();
						}else{
							riskToplimit = ncr.getOneYearSingle();
						}
					}
				}
			}
			if("1".equalsIgnoreCase(singleOrGroup)) {//团单
				if ("1".equals(clauseType) || "2".equals(clauseType)){
					//条款类型为借款人或者建工意外险时
					riskToplimit = ncr.getOneYearGroup();
				}else {
					if ("y".equalsIgnoreCase(unit)) {
						if (maxTime > 1) {
							riskToplimit = ncr.getMoreYearGroup();
						}else{
							riskToplimit = ncr.getOneYearGroup();
						}
					}
					if ("m".equalsIgnoreCase(unit)) {
						if (maxTime > 12) {
							riskToplimit = ncr.getMoreYearGroup();
						}else{
							riskToplimit = ncr.getOneYearGroup();
						}
					}
					if ("d".equalsIgnoreCase(unit)) {
						if (maxTime > 365) {
							riskToplimit = ncr.getMoreYearGroup();
						}else{
							riskToplimit = ncr.getOneYearGroup();
						}
					}
					if ("h".equalsIgnoreCase(unit)) {
						if (maxTime > 8760) {
							riskToplimit = ncr.getMoreYearGroup();
						}else{
							riskToplimit = ncr.getOneYearGroup();
						}
					}
				}
			}
			BigDecimal tem = commRate.add(marketPreserveRate);
			BigDecimal allRate = tem.add(businessPerformanceRate) ;
			if("1".equalsIgnoreCase(agent_type) || "3".equalsIgnoreCase(agent_type) ||"4".equalsIgnoreCase(agent_type) ||"5".equalsIgnoreCase(agent_type)){
				//互联网专属产品
				if("Y".equalsIgnoreCase(ncr.getIsInternetRisk())){
					if(allRate.compareTo(riskToplimit) == 1){
						str = "01" ;
					}
				} if((null == ncr.getIsInternetRisk() || "N".equalsIgnoreCase(ncr.getIsInternetRisk()))  && "1".equalsIgnoreCase(ncr.getRiskType())) {
					if(commRate.compareTo(riskToplimit) == 1){
						str = "02" ;
					}
				}
			}
			if(("6".equalsIgnoreCase(agent_type) || "8".equalsIgnoreCase(agent_type)) && "1".equalsIgnoreCase(agentFeeConfig)){
				if("Y".equalsIgnoreCase(ncr.getIsInternetRisk())){
					if(allRate.compareTo(riskToplimit) == 1){
						str = "03" ;
					}
				} if((null == ncr.getIsInternetRisk() || "N".equalsIgnoreCase(ncr.getIsInternetRisk()))  && "1".equalsIgnoreCase(ncr.getRiskType())) {
					if(commRate.compareTo(riskToplimit) == 1){
						str = "04" ;
					}
				}
			}
		}
		return str;
	}

	@RequestMapping(value = "/queryMainRiskOrFirstRisk")
	@ResponseBody
	public Map<String,String> queryMainRiskOrFirstRisk(String prodCode) throws Exception {
		Map<String,String> map = new HashMap<String, String>();
		NlifeProd prod = nlifeProdDao.queryProdInfoById(prodCode);
		NlifeCoreRisk ncr= nlifePlanConfigService.queryMainRiskOrFirstRisk(prodCode);
		String singleOrGroup = prod.getAppType();//0 个单，1 团单
		String unit = prod.getPppUnit();//保险期限单位，y 年，m 月，d 天，h 时
		Long maxTime = prod.getMaxDays();
		//条款比例上限
		BigDecimal riskToplimit = new BigDecimal(0);
		String isInternetRisk = ncr.getIsInternetRisk();
		String riskType = ncr.getRiskType();
		String clauseType = ncr.getClauseType(); //条款类型：1为借款人意外险，2为建工意外险
		if(null!=ncr.getOneYearSingle()&&null!=ncr.getMoreYearSingle()&&null!=ncr.getOneYearGroup()&&null!=ncr.getMoreYearGroup()){
			if("0".equalsIgnoreCase(singleOrGroup)) {//个单
				if ("1".equals(clauseType) || "2".equals(clauseType)){
					//条款类型为借款人或者建工意外险时
					riskToplimit = ncr.getOneYearSingle();
				}else {
					if ("y".equalsIgnoreCase(unit)) {
						if (maxTime > 1) {
							riskToplimit = ncr.getMoreYearSingle();
						}else{
							riskToplimit = ncr.getOneYearSingle();
						}
					}
					if ("m".equalsIgnoreCase(unit)) {
						if (maxTime > 12) {
							riskToplimit = ncr.getMoreYearSingle();
						}else{
							riskToplimit = ncr.getOneYearSingle();
						}
					}
					if ("d".equalsIgnoreCase(unit)) {
						if (maxTime > 365) {
							riskToplimit = ncr.getMoreYearSingle();
						}else{
							riskToplimit = ncr.getOneYearSingle();
						}
					}
					if ("h".equalsIgnoreCase(unit)) {
						if (maxTime > 8760) {
							riskToplimit = ncr.getMoreYearSingle();
						}else{
							riskToplimit = ncr.getOneYearSingle();
						}
					}
				}
			}
			if("1".equalsIgnoreCase(singleOrGroup)) {//团单
				if ("1".equals(clauseType) || "2".equals(clauseType)){
					//条款类型为借款人或者建工意外险时
					riskToplimit = ncr.getOneYearGroup();
				}else {
					if ("y".equalsIgnoreCase(unit)) {
						if (maxTime > 1) {
							riskToplimit = ncr.getMoreYearGroup();
						}else{
							riskToplimit = ncr.getOneYearGroup();
						}
					}
					if ("m".equalsIgnoreCase(unit)) {
						if (maxTime > 12) {
							riskToplimit = ncr.getMoreYearGroup();
						}else{
							riskToplimit = ncr.getOneYearGroup();
						}
					}
					if ("d".equalsIgnoreCase(unit)) {
						if (maxTime > 365) {
							riskToplimit = ncr.getMoreYearGroup();
						}else{
							riskToplimit = ncr.getOneYearGroup();
						}
					}
					if ("h".equalsIgnoreCase(unit)) {
						if (maxTime > 8760) {
							riskToplimit = ncr.getMoreYearGroup();
						}else{
							riskToplimit = ncr.getOneYearGroup();
						}
					}
				}
			}
		}
		String riskLimit = riskToplimit.toString();
		map.put("isInternetRisk",isInternetRisk);
		map.put("riskToplimit",riskLimit);
		map.put("riskType",riskType);
		return map;

	}
	//查询费用最高的分公司
	@RequestMapping(value = "/queryTopFeeBranch")
	@ResponseBody
	public Map<String,String> queryTopFeeBranch(String agentNo,String prodCode,String isInternetRisk,String riskType) throws Exception {
		Map<String,String> resultMap = new HashMap<String, String>();
		List<CoinFeeConfig> list = coinFeeConfigService.queryCoins(agentNo);
		if(list.size()>0){
			if("Y".equalsIgnoreCase(isInternetRisk)){
				List<Double> allRateList = new ArrayList<Double>();
				for(int i = 0;i< list.size();i++){
					CoinFeeConfig cf= list.get(i);
					Double allRate = cf.getCommRate()+cf.getBusinessRate()+ cf.getMarketRate();
					allRateList.add(allRate);
				}
				Collections.sort(allRateList);
				Double maxFee=allRateList.get(allRateList.size()-1);
				Map<String,String> map;
				map = queryMainRiskOrFirstRisk(prodCode);
				String topRisk = map.get("riskToplimit");
				Double riskToplimit =Double.parseDouble(topRisk)*100;
				if(maxFee>riskToplimit){
					resultMap.put("resultCode","01");
				}else{
					resultMap.put("resultCode","00");
				}
			}
			if((null == isInternetRisk || "".equalsIgnoreCase(isInternetRisk) || "N".equalsIgnoreCase(isInternetRisk))  && "1".equalsIgnoreCase(riskType)) {
				List<Double> commRateList = new ArrayList<Double>();
				for(int i = 0;i< list.size();i++){
					CoinFeeConfig cf= list.get(i);
					Double commRate = cf.getCommRate();
					commRateList.add(commRate);
				}
				Collections.sort(commRateList);
				Double maxFee=commRateList.get(commRateList.size()-1);
				Map<String,String> map;
				map = queryMainRiskOrFirstRisk(prodCode);
				String topRisk = map.get("riskToplimit");
				Double riskToplimit =Double.parseDouble(topRisk)*100;
				if(maxFee>riskToplimit){
					resultMap.put("resultCode","01");
				}else{
					resultMap.put("resultCode","00");
				}
			}
		}
		return resultMap;
	}
	public String selectSingleNodeByRoot(Element root,String path){
		Node node = root.selectSingleNode(path);
		if(node==null){
			return "";
		}else{
			return node.getText();
		}
	}

	private String getAgentTypeByNewBsnsType(String newBsnsType,List<DictDto> newBusinessSource) {
		String agentType = "";
		for (DictDto dictDto : newBusinessSource) {
			if (newBsnsType.equals(dictDto.getCode())){
				if ("1900101".equals(dictDto.getOtherCode2())){
					agentType = "0";
					break;
				}else if ("1900203".equals(dictDto.getOtherCode2())) {
					agentType = "1";
					break;
				}else if ("1900201".equals(dictDto.getOtherCode2())) {
					agentType = "2";
					break;
				}else if ("1900202".equals(dictDto.getOtherCode2())) {
					agentType = "3";
					break;
				}else if ("1900301".equals(dictDto.getOtherCode2())) {
					agentType = "4";
					break;
				}
			}
		}
		return agentType;
	}

	//查询费用最高的分公司
	@RequestMapping(value = "/queryIfInternetPlan")
	@ResponseBody
	public Map<String,String> queryIfInternetPlan(String partnerCode) throws Exception {
		Map<String,String> map = new HashMap<String, String>();
		String flag = iGatewayChannelInfoConfigService.queryIfInternetPlan(partnerCode);
		map.put("flag",flag);
		return map;
	}
	
	//获取业务来源2字典
	@RequestMapping(value = "/getBusinessNature2")
	@ResponseBody
	public List<DictDto> getBusinessNature2(String code){
		List<DictDto> list = DictCache.getDict("BUSINESS_NATURE_2");
		List<DictDto> rslist = new ArrayList<DictDto>();
		for(DictDto dict : list){
			if(dict.getCode().startsWith(code)){
				rslist.add(dict);
			}
		}
		return rslist;
	}
	//获取统信渠道2字典
	@RequestMapping(value = "/getTxChannel2nd")
	@ResponseBody
	public List<DictDto> getTxChannel2nd(String code){
		List<DictDto> list = DictCache.getDict("TX_CHANNEL_2ND");
		List<DictDto> rslist = new ArrayList<DictDto>();
		for(DictDto dict : list){
			if(dict.getCode().startsWith(code)){
				rslist.add(dict);
			}
		}
		return rslist;
	}
	@RequestMapping(value = "/queryUpdateInformation")
	@ResponseBody
	public List<Map<String,Object>> queryUpdateInformation(String prodCode) throws Exception{
		//根据产品编码，获取有几个升级产品,他们的特约名称都是啥
		List<Map<String,Object>> reslut = nlifePlanConfigService.queryUpdateInfomation(prodCode);
		
		return reslut;
	}
	
	@RequestMapping(value="/queryAppType")
	@ResponseBody
	public String queryAppType(String prodCode) throws Exception{
		return nlifeProdDao.queryProdInfoById(prodCode).getAppType();
		
	}
}
